package tu.j2ee.tasktracker.service.security;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import tu.j2ee.tasktracker.dao.CustomUserDAO;
import tu.j2ee.tasktracker.domain.CustomUser;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private CustomUserDAO userDao;

	@Override
	public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
		CustomUser customUser = userDao.findByUsername(name);
		
		if(customUser == null) {
			throw new UsernameNotFoundException("Username not found: " + name);
		}
		
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		authorities.add(new SimpleGrantedAuthority(customUser.getRole().name()));
		return new User(customUser.getUsername(), customUser.getPassword(), customUser.isEnabled(), true, true, true, authorities);
	}

}
